package com.qingzhuge.common;

import org.apache.commons.lang3.StringUtils;
import org.springframework.context.i18n.LocaleContextHolder;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;

/**
 * @author : zero.xiao
 * @description : 加载配置
 * @modified :
 */
public final class Resources {
    /** 国际化信息 */
    private static final Map<String, ResourceBundle> MESSAGES = new HashMap<>();

    /** 国际化信息 */
    public static String getMessage(String key, Object... params) {
        return getMessageByModule(null,key,params);
    }
    /** 国际化信息 */
    public static String getMessageByModule(String module,String key, Object... params) {
        Locale locale = LocaleContextHolder.getLocale();
        String language = locale.getLanguage();
        if (StringUtils.isNotBlank(module)) {
            language += module;
        }
        ResourceBundle message = MESSAGES.get(language);
        if (message == null) {
            synchronized (MESSAGES) {
                message = MESSAGES.get(language);
                if (message == null) {
                    message = getBundle(locale,module);
                    MESSAGES.put(language, message);
                }
            }
        }
        if (params != null && params.length > 0) {
            return String.format(message.getString(key), params);
        }else {
            return message.getString(key);
        }
    }

    /**
     *
     * @param locale 语言种类
     * @param module 项目模块
     * @return 语言资源
     */
    private static ResourceBundle getBundle(Locale locale,String module) {
        if (StringUtils.isNotBlank(module)){
            return ResourceBundle.getBundle("i18n/messages_"+module, locale);
        }else {
            return ResourceBundle.getBundle("i18n/messages", locale);
        }
    }

    /** 清除国际化信息 */
    public static void flushMessage() {
        MESSAGES.clear();
    }
}
